use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, Read, Write};
use std::thread;
use std::time::{Duration, Instant};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /*let resp = reqwest::get("https://httpbin.org/ip")
    .await?
    .json::<HashMap<String, String>>()
    .await?;*/

    let resp =
        reqwest::get("http://120.55.167.227:9000/boyebio/apkFiles/CATACURE_V1.0.0_build_1.apk")
            .await?
            .bytes()
            .await?;
    println!("{:#?}", resp);
    Ok(())
}

//测试同步请求，阻塞
/*#[test]
fn test() {
    // let client = reqwest::Client::new();
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(60))
        .connect_timeout(Duration::from_secs(10))
        .build().unwrap();
    let resp = client.get("http://192.168.0.100:9011/external/backup_20231212091228.zip").send().bytes().into();

    // let resp = reqwest::blocking::get("http://192.168.0.100:9011/external/backup_20231212091228.zip").unwrap()
    //     .bytes().unwrap();
    File::create("test.zip").unwrap().write(resp).unwrap();
    println!("{:#?}", resp);
}*/

//测试下载文件。阻塞下载
#[test]
fn test1() {
    let start = Instant::now();

    // 1. 初始化请求
    let resp =
        reqwest::blocking::get("http://192.168.0.100:9000/hgbio/export/tmp/19193bd9798c4f3b9ea826ebc916ff82/backup_20231211201920.byc")
            .unwrap();

    // 2. 检查响应状态
    if !resp.status().is_success() {
        println!("HTTP请求错误");
        return;
    }

    // 3. 获取内容长度
    let content_length = resp.content_length().unwrap();

    // 4. 创建文件并写入响应 Body
    let mut file = std::fs::File::create("file.byc").unwrap();
    let mut content = resp.bytes().unwrap();
    file.write_all(&content.to_vec())
        .expect("TODO: panic message");

    // 5. 校验长度一致
    if content_length != file.metadata().unwrap().len() {
        println!("文件长度不一致");
        return;
    }

    println!("文件下载完成");

    println!(">>>>下载文件总用时：{:?}", start.elapsed());
}
